<template>
    <view class="bg">
        <view class="" :style="{height: menuTopHeight + 'px'}"></view>
        <view class="menu-box" :style="{height: menuHeight + 'px'}">
            <u-icon name="arrow-left" color="#fff" size="20" @click="goBack"></u-icon>
            <view class="navigate-title">支付确认</view>
        </view>
        <view class="bg-circle">
            <u-image width="100%" height="370rpx" :src="getServerStatic('/static/images/b4.png')"></u-image>
        </view>
    </view>
    <view class="container">
        <view class="userinfo">
            <u-avatar src="/static/images/avatar.png" size="116rpx" v-if="doctorInfo.avatar.length <= 0"></u-avatar>
            <u-avatar :src="checkAndFixUrl(doctorInfo.avatar)" size="116rpx" v-else></u-avatar>
            <view class="content-box">
                <view class="name-box">
                    <view class="name">{{ doctorInfo.name }}</view>
                    <view class="tag">{{ doctorInfo.job_title }}</view>
                </view>
                <view class="name1">{{ doctorInfo.department_name }}</view>
            </view>
        </view>

        <!-- 费用信息 -->
        <view class="pay-info">
            <u-cell-group>
                <u-cell clickable title="就诊日期" titleStyle="font-size: 28rpx;color: #B3BCCC;" :value="orderInfo.treatment_date + ' ' + orderInfo.treatment_time + '-' + orderInfo.treatment_end_time">
                    <template #icon>
                        <view>
                            <u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a29.png')" ></u-image>
                        </view>
                    </template>
                </u-cell>
                <u-cell clickable title="就诊人" titleStyle="font-size: 28rpx;color: #B3BCCC;" :value="orderInfo.patient_name">
                    <template #icon>
                        <view>
                            <u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a30.png')"></u-image>
                        </view>
                    </template>
                </u-cell>
                <u-cell clickable title="手机号码" titleStyle="font-size: 28rpx;color: #B3BCCC;" :value="orderInfo.patient_mobile">
                    <template #icon>
                        <view>
                            <u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a31.png')"></u-image>
                        </view>
                    </template>
                </u-cell>
                <u-cell clickable :border="false" title="挂号费" titleStyle="font-size: 28rpx;color: #B3BCCC;" :value="orderInfo.price">
                    <template #icon>
                        <view>
                            <u-image width="60rpx" height="60rpx" :src="getServerStatic('/static/images/a34.png')"></u-image>
                        </view>
                    </template>
                    <template #value>
                        <view class="price-box">
                            <text style="font-size: 28rpx;">￥</text>
                            <text style="font-size: 38rpx;">{{ orderInfo.price }}</text>
                        </view>
                    </template>
                </u-cell>
            </u-cell-group>
        </view>

        <!-- 支付选择 -->
        <view class="payment-select-box">
            <u-radio-group v-model="paymentWay" placement="column" @change="handlePaymentWayChange">
                <view class="payment-item" @click="handleSelectPayment('wechat')">
                    <view class="left">
                        <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a40.png')"></u-image>
                        <view class="pay-name">微信支付</view>
                    </view>
                    <view class="right">
                        <u-radio activeColor="#516DDB" name="wechat"></u-radio>
                    </view>
                </view>
                <view class="payment-item center" @click="handleSelectPayment('balance')">
                    <view class="left">
                        <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a41.png')"></u-image>
                        <view class="pay-name">余额支付</view>
                        <view class="pay-tip">当前余额：{{userStore.store_balance}}元</view>
                    </view>
                    <view class="right">
                        <u-radio activeColor="#516DDB" name="balance"></u-radio>
                    </view>
                </view>
                <view class="payment-item" @click="handleSelectPayment('coupon')">
                    <view class="left">
                        <u-image width="40rpx" height="40rpx" :src="getServerStatic('/static/images/a42.png')"></u-image>
                        <view class="pay-name">抵扣券支付</view>
                    </view>
                    <view class="right">
                        <u-radio activeColor="#516DDB" name="coupon"></u-radio>
                    </view>
                </view>
            </u-radio-group>
        </view>
    </view>

    <view class="btn">
        <u-button throttleTime="1000"
                  :customStyle="{height: '86rpx', boxShadow: '0rpx 4rpx 34rpx 1rpx rgba(87,129,240,0.4)', letterSpacing: '.1rem'}" :hairline="false"
                  type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                  @click="goSuccess">立即支付</u-button>
    </view>
</template>

<script setup>
    import {ref, reactive, readonly} from 'vue'
    import {onLoad, onShow} from '@dcloudio/uni-app'
    import {
        useHeight
    } from '@/hooks/useMenuHeight'
    import {getOrderDetail, initiatePayment} from "@/api/order";
    import {getDoctorDetailByID} from "@/api/doctor";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";
    import useUniAPi from "@/hooks/useUniAPi";
    import {useUserStore} from "@/store";
    const { navigateTo, redirectTo, goBack, payment } = useUniAPi()
    const {
        menuHeight,
        menuTopHeight
    } = useHeight()

    // 用户store
    const userStore = useUserStore();

    // 支付方式
    const paymentWay = ref('wechat')
    const handlePaymentWayChange = (e) => {
        paymentWay.value = '' + e;
    }

    const handleSelectPayment = (way) => {
        paymentWay.value = way;
    }

    // 订单信息
    const orderInfo = reactive({
        patient_name: "",
        patient_sex: "",
        patient_age: "",
        patient_mobile: "",
        hospital_name: "",
        project_name: "",
        doctor_name: "",
        treatment_date: "",
        treatment_time: "",
        treatment_end_time: "",
        price: "0.00",
        status: 0,
        payment_time: 0,
        order_no: '',
        trade_no: '',
        cancel_reason: "",
        cancel_type: 1,
        cancel_app_time: "",
    })

    // 医生信息
    const doctorInfo = reactive({
        name: '',
        avatar: '',
        job_title: '',
        department_name: ''
    })

    const orderId = ref(0)
    onLoad((evt) => {
        if (!evt?.orderId) {
            goBack()
        }

        orderId.value = evt.orderId
        // 同步用户信息
        userStore.syncUserInfo()
        handleGetOrderDetail()
    })

    const handleGetOrderDetail = async () => {

        const {code, data, message} = await getOrderDetail({orderId: orderId.value})
        const doctorResult = await getDoctorDetailByID({doctor_id: data.doctor_id})
        if (code == 1 && doctorResult.code == 1) {
            Object.assign(orderInfo, data)
            Object.assign(doctorInfo, doctorResult.data)
        } else {
            uni.showToast({
                mask: true,
                title: '请求异常',
                icon: 'error'
            })
            setTimeout(() => {
                goBack()
            },800)
        }
    }

    const goSuccess = async () => {

        console.log('发起支付ID', orderId.value)
        uni.showLoading({
            title: '加载中'
        });
        const { code, data, message } = await initiatePayment({orderId: orderId.value, method: paymentWay.value})

        console.log('发起支付', data)
        uni.hideLoading();
        if (code == 1) {
            if (paymentWay.value == 'wechat') {
                const result =  await payment(data)
                console.log('发起支付结果',result)
                // {errMsg: "requestPayment:ok"}
                if (result?.errMsg && result.errMsg == 'requestPayment:ok') {
                    console.log('支付完成')
                    uni.showToast({
                        mask: true,
                        title: '支付完成!',
                        icon: 'success'
                    })
                    setTimeout(() => {
                        uni.switchTab({
                            url: `/pages/mine/mine`
                        })
                    }, 800)
                    // uni.navigateTo({
                    //     url: `/mine/reservation/success?amount=${orderInfo.price}`
                    // })
                } else {
                    uni.showToast({
                        mask: true,
                        title: '取消支付!',
                        icon: 'none'
                    })
                }
            } else {
                uni.showToast({
                    mask: true,
                    title: '支付完成!',
                    icon: 'success'
                })
                setTimeout(() => {
                    uni.switchTab({
                        url: `/pages/mine/mine`
                    })
                }, 800)
            }

        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
            return false
        }
        return false

    }
</script>

<style scoped lang="scss">
.bg {
    width: 100vw;
    height: 370rpx;
    position: relative;

    .menu-box {
        padding-left: 26rpx;
        color: #fff;
        display: flex;
        align-items: center;

        .navigate-title {
            color: #fff;
            font-size: 36rpx;
            color: #FFFFFF;
            margin-left: 18rpx;
        }
    }

    // z-index: -1;
    .bg-circle {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        width: 100%;
        height: 100%;
    }
}

.container {
    position: relative;
    z-index: 19;
    padding: 0 26rpx;
    margin-top: -150rpx;
}

.userinfo {
    padding: 30rpx 28rpx;
    background: #fff;
    border-radius: 20rpx;
    @include center();

    .content-box {
        flex: 1;
        margin-left: 24rpx;

        .name-box {
            @include start();

            .name {
                font-size: 36rpx;
                color: #222222;
            }

            .tag {
                font-size: 24rpx;
                color: #606672;
                margin-left: 16rpx;
            }
        }

        .name1 {
            color: #516DDB;
            margin-top: 12rpx;
        }
    }
}

.pay-info {
    background: #FFFFFF;
    border-radius: 30rpx;
    margin-top: 30rpx;

}

.price-box {
    color: #D67354;
}

.payment-select-box {
    background: #FFFFFF;
    border-radius: 30rpx;
    padding: 30rpx;
    margin-top: 20rpx;
    .payment-item {
        @include between(100%);
        .left {
            @include start();
            .pay-name {
                color: #000000;
                font-size: 28rpx;
                margin-left: 16rpx;
            }
            .pay-tip {
                margin-left: 16rpx;
                color: #B3BCCC;
            }
        }
    }
    .center {
        margin: 20rpx 0;
    }
}
.btn {
    padding: 0 55rpx;
    width: 100%;
    position: fixed;
    left: 50%;
    bottom: 70rpx;
    transform: translateX(-50%);
    z-index: 9;
}
</style>
